from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework_jwt.authentication import jwt_decode_handler

from six_it.serializers.serializers import SpitSerializer
from six_it.models import Spit


class SpitViewSet(ModelViewSet):
    serializer_class = SpitSerializer
    queryset = Spit.objects.all().order_by("-publishtime")

    # 禁用drf自带的认证机制
    # def perform_authentication(self, request):
    #     pass
    # def create(self, request, *args, **kwargs):
    #     pass
    # def update_thumbup(self, request, *args, **kwargs):
    #     pass
    # def collect(self, request, *args, **kwargs):
    #     pass
    #获取所有一级吐槽 spit/
    def list(self, request,  *args, **kwargs):

        spitlist = self.get_queryset().filter(parent=None)

        SpitList = []

        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            for spit in spitlist:
                collet_flag = redis_conn.hget("spit_collect_%s"%user.id,str(spit.id))
                thumbup_flag = redis_conn.hget("spit_thumbup_%s"%user.id,str(spit.id))
                if collet_flag:
                    spit.collected =True
                if thumbup_flag:
                    spit.thumbup = True
                SpitList.append(spit)
        else:
            SpitList = spitlist

        res = self.get_serializer(instance=SpitList,many=True)

        return Response(res.data)
class SpitThumbupAPIView(APIView):

    def put(self,request,id):

        try:
            token = self.request.auth
            toke_user = jwt_decode_handler(token)
            user_id = toke_user["user_id"]
        except Exception as e:
            return Response('点赞失败，请先登录', status=404)

        redis_conn = get_redis_connection('spit')
        # 判断key（'thumbup_%s' % id）中是否有value（user_id）
        if redis_conn.sismember('thumbup_%s' % id, user_id):
            redis_conn.srem('thumbup_%s' % id, user_id)
            spit = Spit.objects.get(id=id)
            spit.thumbup -= 1
            spit.save()
            return Response({
                'message': '取消点赞',
                'success': True
            })
        else:
            redis_conn.sadd('thumbup_%s' % id, user_id)
            spit = Spit.objects.get(id=id)
            spit.thumbup += 1
            spit.save()
            return Response({
                'message':'点赞成功',
                'success':True
            })
class SpitCollectAPIView(APIView):

    def put(self,request,id):

        try:
            token = self.request.auth
            toke_user = jwt_decode_handler(token)
            user_id = toke_user["user_id"]
        except Exception as e:
            return Response('收藏失败，请先登录',status=404)

        redis_conn = get_redis_connection('spit')
        # 判断key（'collect_%s' % id）中是否有value（user_id）
        if redis_conn.sismember('collect_%s' % id, user_id):
            redis_conn.srem('collect_%s' % id, user_id)
            spit = Spit.objects.get(id=id)
            return Response({
                'message': '取消收藏',
                'success': True
            })
        else:
            redis_conn.sadd('collect_%s' % id, user_id)
            spit = Spit.objects.get(id=id)
            return Response({
                'message':'收藏成功',
                'success':True
            })